/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.skatiger.jrove.servlet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

import javax.servlet.ServletContext;

import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.ResourceResolver;
import org.skatiger.jrove.util.AssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServletResourceResolver implements ResourceResolver {
    private static final Logger logger = LoggerFactory
            .getLogger(ServletResourceResolver.class);

    private URL getResourceUrl(String path) throws MalformedURLException {
        URL url = servletContext.getResource(path);
        if (logger.isDebugEnabled()) {
            logger.debug("get resource from servletContext");
        }
        if (url == null) {
            if (resourceExist(path)) {
                url = getUrlForResourceAsStream(path);
            }
        }
        return url;
    }

    // Construct URL with special URLStreamHandler for proxying
    // ServletContext.getResourceAsStream()
    private URL getUrlForResourceAsStream(String path) throws MalformedURLException {
        URLStreamHandler handler = new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL u) throws IOException {
                final String file = u.getFile();
                return new URLConnection(u) {
                    @Override
                    public void connect() throws IOException {
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        logger.debug("Opening internal url to " + file);
                        InputStream stream = servletContext
                                .getResourceAsStream(file);
                        if (stream == null) {
                            throw new FileNotFoundException(
                                    "Cannot open resource " + file);
                        }
                        return stream;
                    }

                    @Override
                    public long getLastModified() {

                        return super.getLastModified();
                    }
                };
            }
        };
        return new URL("internal", null, 0, path, handler);
        // return servletContext.getResource(path);
    }

    // This method could be used above to provide a 'fail fast' if a
    // resource
    // doesnt exist. Otherwise, the URL will fail on the first access.
    private boolean resourceExist(String path) {
        if ("/".equals(path)) {
            // The root context exists always
            return true;
        }
        InputStream stream = servletContext.getResourceAsStream(path);
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // Ignore here, since we donnot wanted to read from this
                // resource anyway
            }
            return true;
        }
        return false;
    }

    protected ServletContext servletContext;

    public ServletResourceResolver() {

    }

    public ServletContext getServletContext() {
        return servletContext;
    }

    public void prepareServletContext(ServletContext servletContext) {
        AssertUtil.notNull(servletContext);
        this.servletContext = servletContext;
    }

    public URL resolveUrl(String path) {
        try {
            URL url = getResourceUrl(path);
            if (logger.isDebugEnabled()) {
                logger.debug("load path from ServletResourceResolver " + url);
            }
            return url;
        } catch (IOException e) {
            throw new JroveException(e);
        }
    }

    @Override
    public String toString() {
        return "ServletResourceResolver";
    }
}
